package com.fl.niu.common.util;

import cn.hutool.core.util.StrUtil;
import org.bytedeco.javacv.FFmpegFrameGrabber;
import org.bytedeco.javacv.Frame;
import org.bytedeco.javacv.Java2DFrameConverter;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import ws.schild.jave.*;

import javax.imageio.ImageIO;
import java.awt.*;
import java.awt.image.BufferedImage;
import java.io.*;
import java.math.BigDecimal;
import java.math.RoundingMode;
import java.net.HttpURLConnection;
import java.net.URL;
import java.nio.channels.FileChannel;
import java.util.HashMap;
import java.util.Map;

/**
 * @program:niu-cloud
 * @Author memory
 * @Date 2020/10/29 9:21
 * @description
 **/
public class VideoUtil {
    private static final Logger log = LoggerFactory.getLogger(MinioUtil.class);
    public static File compressionVideo(String href){
        try{
            // 缓存到临时目录，压缩上传完到远程服务器上之后，记得删除源视频
            String savePath = "/tmp/tempVideo/";
            long time = System.currentTimeMillis();
            URL url=new URL(href);
            HttpURLConnection connection=(HttpURLConnection)url.openConnection();
            connection.setConnectTimeout(600*1000);
            connection.setRequestProperty("User-Agent","Mozilla/5.0 (Windows NT 6.1; WOW64) AppleWebKit/537.36 (KHTML, like Gecko) Chrome/57.0.2987.110 Safari/537.36");
            InputStream in=connection.getInputStream();
            String fileName =  "zip" + href.substring(href.lastIndexOf("/") + 1);
            File saveDir = new File(savePath);
            if(!saveDir.exists()){
                saveDir.mkdirs();
            }
            File file = new File(savePath + fileName);
            OutputStream out=new FileOutputStream(file);
            byte[] bytes=new byte[1024];
            int len = 0;
            while((len=in.read(bytes))!=-1){
                out.write(bytes,0,len);
            }
            out.close();
            in.close();
            System.out.println("下载+压缩 总耗时：" + (System.currentTimeMillis() - time)/1000);
            return compressionVideo(file, fileName);
        }catch (Exception e){
            e.printStackTrace();
        }
        return null;
    }

    /**
     * 传视频File对象，返回压缩后File对象信息
     * @param source
     */
    public static File compressionVideo(File source,String picName) {
        if(source == null){
            return null;
        }
        String newPath = source.getAbsolutePath().substring(0, source.getAbsolutePath().lastIndexOf("\\")).concat(picName);
        File target = new File(newPath);
        try {
            MultimediaObject object = new MultimediaObject(source);
            AudioInfo audioInfo = object.getInfo().getAudio();
            // 根据视频大小来判断是否需要进行压缩,
            int maxSize = 100;
            double mb = Math.ceil(source.length()/ 1048576);
            int second = (int)object.getInfo().getDuration()/1000;
            BigDecimal bd = new BigDecimal(String.format("%.4f", mb/second));
            System.out.println("开始压缩视频了--> 视频每秒平均 "+ bd +" MB ");
            // 视频 > 100MB, 或者每秒 > 0.5 MB 才做压缩， 不需要的话可以把判断去掉
            boolean temp = mb > maxSize || bd.compareTo(new BigDecimal(0.5)) > 0;
            if(temp){
                long time = System.currentTimeMillis();
                //TODO 视频属性设置
                int maxBitRate = 128000;
                int maxSamplingRate = 44100;
                int bitRate = 800000;
                int maxFrameRate = 20;
                int maxWidth = 1280;

                AudioAttributes audio = new AudioAttributes();
                // 设置通用编码格式
                audio.setCodec("aac");
                // 设置最大值：比特率越高，清晰度/音质越好
                // 设置音频比特率,单位:b (比特率越高，清晰度/音质越好，当然文件也就越大 128000 = 182kb)
                if(audioInfo.getBitRate() > maxBitRate){
                    audio.setBitRate(new Integer(maxBitRate));
                }

                // 设置重新编码的音频流中使用的声道数（1 =单声道，2 = 双声道（立体声））。如果未设置任何声道值，则编码器将选择默认值 0。
                audio.setChannels(audioInfo.getChannels());
                // 采样率越高声音的还原度越好，文件越大
                // 设置音频采样率，单位：赫兹 hz
                // 设置编码时候的音量值，未设置为0,如果256，则音量值不会改变
                // audio.setVolume(256);
                if(audioInfo.getSamplingRate() > maxSamplingRate){
                    audio.setSamplingRate(maxSamplingRate);
                }

                //TODO 视频编码属性配置
                VideoInfo videoInfo = object.getInfo().getVideo();
                VideoAttributes video = new VideoAttributes();
                video.setCodec("h264");
                //设置音频比特率,单位:b (比特率越高，清晰度/音质越好，当然文件也就越大 800000 = 800kb)
                if(videoInfo.getBitRate() > bitRate){
                    video.setBitRate(bitRate);
                }

                // 视频帧率：15 f / s  帧率越低，效果越差
                // 设置视频帧率（帧率越低，视频会出现断层，越高让人感觉越连续），视频帧率（Frame rate）是用于测量显示帧数的量度。所谓的测量单位为每秒显示帧数(Frames per Second，简：FPS）或“赫兹”（Hz）。
                if(videoInfo.getFrameRate() > maxFrameRate){
                    video.setFrameRate(maxFrameRate);
                }

                // 限制视频宽高
                int width = videoInfo.getSize().getWidth();
                int height = videoInfo.getSize().getHeight();
                if(width > maxWidth){
                    float rat = (float) width / maxWidth;
                    video.setSize(new VideoSize((maxWidth/2)*2,((int)(height/rat)/2)*2));
                }

                EncodingAttributes attr = new EncodingAttributes();
                attr.setFormat("mp4");
                attr.setAudioAttributes(audio);
                attr.setVideoAttributes(video);

                // 速度最快的压缩方式， 压缩速度 从快到慢： ultrafast, superfast, veryfast, faster, fast, medium,  slow, slower, veryslow and placebo.
//                attr.setPreset(PresetUtil.VERYFAST);
//                attr.setCrf(27);
//                // 设置线程数
//                attr.setEncodingThreads(Runtime.getRuntime().availableProcessors()/2);

                Encoder encoder = new Encoder();
                encoder.encode(new MultimediaObject(source), target, attr);
                System.out.println("压缩总耗时：" + (System.currentTimeMillis() - time)/1000);
                return target;
            }
        } catch (Exception e) {
            e.printStackTrace();
        }finally {
            if(target.length() > 0){
                source.delete();
            }
        }
        return source;
    }


    /**
     * 获取视频大小
     * @param source
     * @return
     */
    @SuppressWarnings({ "resource" })
    public static BigDecimal ReadVideoSize(File source) {
        FileChannel fc = null;
        try {
            FileInputStream fis = new FileInputStream(source);
            fc = fis.getChannel();
            BigDecimal fileSize = new BigDecimal(fc.size());
            return fileSize.divide(new BigDecimal(1048576), 2, RoundingMode.HALF_UP);
        } catch (FileNotFoundException e) {
            e.printStackTrace();
        } catch (IOException e) {
            e.printStackTrace();
        } finally {
            if (null != fc) {
                try {
                    fc.close();
                } catch (IOException e) {
                    e.printStackTrace();
                }
            }
        }
        return null;
    }

    /**
     * 使用 FFmpeg 截取视频第几帧生成图片
     *
     * @param videoPath 视频路径
     * @param frame     第几帧
     * @param utilPath  工具包地址
     * @return String    图片的相对路劲
     */
//    public static String processImg(String videoPath, String frame, String utilPath) {
//        File file = new File(videoPath);
//        if (!file.exists()) {
//            System.err.println("路径[" + videoPath + "]对应的视频文件不存在!");
//            return null;
//        }
//        List<String> commands = new java.util.ArrayList<String>();
//        commands.add(utilPath);
//        commands.add("-i");
//        commands.add(videoPath);
//        commands.add("-y");
//        commands.add("-f");
//        commands.add("image2");
//        commands.add("-ss");
//        commands.add(frame);    // 这个参数是设置截取视频多少秒时的画面
//        commands.add("-t");
//        commands.add("0.001");
//        commands.add("-s");
//        commands.add("800x1200"); // 宽X高
//        String imgPath = videoPath.substring(0, videoPath.lastIndexOf(".")) + "-cover" + ".jpg";
//        commands.add(imgPath);
//        try {
//            ProcessBuilder builder = new ProcessBuilder();
//            builder.command(commands);
//            builder.redirectErrorStream(true);
//            LOGGER.debug("视频截图开始...");
//            Process process = builder.start();
//            InputStream in = process.getInputStream();
//            // 写入本地
//            FileUtil.writeToLocal(imgPath, in);
//            LOGGER.debug("截取成功");
//            return imgPath;
//        } catch (Exception e) {
//            e.printStackTrace();
//            return null;
//        }
//    }

    /**
     * 通过Javacv的方式获取视频截图
     *
     * @param filePath 视频文件路径
     * @return Map<String, Object>
     */
    public static Map<String, Object> getScreenshot(String filePath) {
        try {
            log.debug("截取视频截图开始：" + System.currentTimeMillis());
            Map<String, Object> result = new HashMap<String, Object>();
            FFmpegFrameGrabber grabber = FFmpegFrameGrabber.createDefault(filePath);

            // 第一帧图片存储位置
            String targerFilePath = filePath.substring(0, filePath.lastIndexOf("\\"));
            // 视频文件名
            String fileName = filePath.substring(filePath.lastIndexOf("\\") + 1);
            // 图片名称
            String targetFileName = fileName.substring(0, fileName.lastIndexOf("."));
            log.debug("视频路径是：" + targerFilePath);
            log.debug("视频文件名：" + fileName);
            log.debug("图片名称是：" + targetFileName);

            grabber.start();
            //设置视频截取帧（默认取第一帧）
            Frame frame = grabber.grabImage();
            //视频旋转度
            String rotate = grabber.getVideoMetadata("rotate");
            Java2DFrameConverter converter = new Java2DFrameConverter();
            //绘制图片
            BufferedImage bi = converter.getBufferedImage(frame);
            if (rotate != null) {
                // 旋转图片
                bi = rotate(bi, Integer.parseInt(rotate));
            }
            //图片的类型
            String imageMat = "jpg";
            //图片的完整路径
            String imagePath = targerFilePath + File.separator + targetFileName + "." + imageMat;
            //创建文件
            File output = new File(imagePath);
            ImageIO.write(bi, imageMat, output);

            //拼接Map信息
            result.put("videoWide", bi.getWidth());
            result.put("videoHigh", bi.getHeight());
            long duration = grabber.getLengthInTime() / (1000 * 1000);
            result.put("rotate", StrUtil.isBlank(rotate) ? "0" : rotate);
            result.put("format", grabber.getFormat());
            result.put("imgPath", output.getPath());
            result.put("time", duration);
            log.debug("视频的宽:" + bi.getWidth());
            log.debug("视频的高:" + bi.getHeight());
            log.debug("视频的旋转度：" + rotate);
            log.debug("视频的格式：" + grabber.getFormat());
            log.debug("此视频时长（s/秒）：" + duration);
            grabber.stop();
            log.debug("截取视频截图结束：" + System.currentTimeMillis());
            return result;
        } catch (Exception e) {
//            log.error("VideoUtil getScreenshot fail: {}", ExceptionStackTrace.printStackTrace(e));
            return null;
        }
    }


    /**
     * 根据视频旋转度来调整图片
     *
     * @param src   BufferedImage
     * @param angel angel	视频旋转度
     * @return BufferedImage
     */
    public static BufferedImage rotate(BufferedImage src, int angel) {
        int src_width = src.getWidth(null);
        int src_height = src.getHeight(null);
        int type = src.getColorModel().getTransparency();
        Rectangle rect_des = calcRotatedSize(new Rectangle(new Dimension(src_width, src_height)), angel);
        BufferedImage bi = new BufferedImage(rect_des.width, rect_des.height, type);
        Graphics2D g2 = bi.createGraphics();
        g2.translate((rect_des.width - src_width) / 2, (rect_des.height - src_height) / 2);
        g2.rotate(Math.toRadians(angel), src_width / 2, src_height / 2);
        g2.drawImage(src, 0, 0, null);
        g2.dispose();
        return bi;
    }

    /**
     * 计算图片旋转大小
     *
     * @param src   Rectangle
     * @param angel int
     * @return Rectangle
     */
    public static Rectangle calcRotatedSize(Rectangle src, int angel) {
        if (angel >= 90) {
            if (angel / 90 % 2 == 1) {
                int temp = src.height;
                src.height = src.width;
                src.width = temp;
            }
            angel = angel % 90;
        }
        double r = Math.sqrt(src.height * src.height + src.width * src.width) / 2;
        double len = 2 * Math.sin(Math.toRadians(angel) / 2) * r;
        double angel_alpha = (Math.PI - Math.toRadians(angel)) / 2;
        double angel_dalta_width = Math.atan((double) src.height / src.width);
        double angel_dalta_height = Math.atan((double) src.width / src.height);
        int len_dalta_width = (int) (len * Math.cos(Math.PI - angel_alpha - angel_dalta_width));
        int len_dalta_height = (int) (len * Math.cos(Math.PI - angel_alpha - angel_dalta_height));
        int des_width = src.width + len_dalta_width * 2;
        int des_height = src.height + len_dalta_height * 2;
        return new Rectangle(new Dimension(des_width, des_height));
    }
    /**
     * 截取视频获得指定帧的图片
     *
     * @param video  源视频文件
     * @param picPath 截图存放路径
     */
    public static File getVideoPic(File video, String picPath) {
        FFmpegFrameGrabber ff = new FFmpegFrameGrabber(video);
        File picFile = null;
        try {
            ff.start();
            // 截取中间帧图片(具体依实际情况而定)
            int i = 0;
            int length = ff.getLengthInFrames();
            int middleFrame = length / 2;
            org.bytedeco.javacv.Frame frame = null;
            frame = ff.grabImage();
//            while (i < length) {
//
//                if ((i > middleFrame) && (frame.image != null)) {
//                    break;
//                }
//                i++;
//            }
            // 截取的帧图片
            Java2DFrameConverter converter = new Java2DFrameConverter();
            BufferedImage srcImage = converter.getBufferedImage(frame);
//            int srcImageWidth = srcImage.getWidth();
//            int srcImageHeight = srcImage.getHeight();
//            // 对截图进行等比例缩放(缩略图)
//            int width = 480;
//            int height = (int) (((double) width / srcImageWidth) * srcImageHeight);
//            BufferedImage thumbnailImage = new BufferedImage(width, height, BufferedImage.TYPE_3BYTE_BGR);
//            thumbnailImage.getGraphics().drawImage(srcImage.getScaledInstance(width, height, Image.SCALE_SMOOTH), 0, 0, null);
            picFile = new File(picPath);
            ImageIO.write(srcImage, "jpg", picFile);
            ff.stop();
        } catch (IOException e) {
            e.printStackTrace();
        }
        return picFile;
    }
}
